package com.ark.service.impl;

import com.ark.constant.CacheConstant;
import com.ark.constant.MessageConstant;
import com.ark.constant.StatusConstant;
import com.ark.context.BaseContext;
import com.ark.dto.DishDTO;
import com.ark.dto.DishPageQueryDTO;
import com.ark.entity.Dish;
import com.ark.entity.DishFlavor;
import com.ark.exception.DeletionNotAllowedException;
import com.ark.mapper.DishFlavorMapper;
import com.ark.mapper.DishMapper;
import com.ark.mapper.SetmealDishMapper;
import com.ark.result.PageResult;
import com.ark.service.DishService;
import com.ark.utils.GsonUtil;
import com.ark.vo.DishVO;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Service
@Slf4j
@RequiredArgsConstructor
public class DishServiceImpl implements DishService {

    private final DishMapper dishMapper;

    private final DishFlavorMapper dishFlavorMapper;

    private final SetmealDishMapper setmealDishMapper;

    private final RedisTemplate<String,Object> redisTemplate;


    @Override
    @Transactional
    public void saveWithFlavor(DishDTO dishDTO) {
        //1.向菜品表插入数据
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);

        dishMapper.insert(dish);
        Long id = dish.getId();
//        log.info("自增id: {}",id);
//        log.info("dish: {}", dish);

        //2.向口味表插入n条数据
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (flavors != null && !flavors.isEmpty()) {
            flavors.forEach(flavor -> flavor.setDishId(id));
            dishFlavorMapper.insert(flavors);
        }
        BaseContext.clear();
    }

    @Override
    public PageResult<DishVO> pageQuery(DishPageQueryDTO dishPageQueryDTO) {
        PageHelper.startPage(dishPageQueryDTO.getPage(),dishPageQueryDTO.getPageSize());
        Page<DishVO> page = dishMapper.pageQuery(dishPageQueryDTO);
        return new PageResult<>(page.getTotal(),page.getResult());
    }

    @Override
    @Transactional
    public void deleteBatch(List<Long> ids) {
        //判断当前菜品是否能被删除(不在起售中的菜品)
        List<Dish> dishes = dishMapper.selectByIds(ids);
        dishes.forEach(dish -> {
            if(Objects.equals(dish.getStatus(), StatusConstant.ENABLE)){
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
        });

        //判断当前菜品是否被套餐关联
        List<Long> setmealIds = setmealDishMapper.getSetmealIdsByDishIds(ids);
        if(setmealIds != null && !setmealIds.isEmpty()){
            //当前菜品被套餐关联了,不能删除
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }
        //删除菜品表中菜品数据
        dishMapper.deleteByIds(ids);
        //删除菜品关联的口味数据
//        dishFlavorMapper.deleteByIds(ids);
        dishFlavorMapper.deleteByDishIds(ids);
    }

    @Override
    public DishVO getByIdWithFlavor(Long id) {
        //根据id查询菜品数据
        Dish dish = dishMapper.selectById(id);

        //根据菜品id查询口味数据
        List<DishFlavor> dishFlavors = dishFlavorMapper.getByDishId(id);

        //将查询到的数据封装到VO
        DishVO dishVO = new DishVO();
        BeanUtils.copyProperties(dish,dishVO);
        dishVO.setFlavors(dishFlavors);

        return dishVO;
    }

    @Override
    @Transactional
    public void updateWithFlavor(DishDTO dishDTO) {
        //修改菜品表基本信息
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        dishMapper.updateById(dish);

        //删除原有口味数据
        dishFlavorMapper.deleteByDishId(dishDTO.getId());

        //重新插入口味数据
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (flavors != null && !flavors.isEmpty()) {
            flavors.forEach(flavor -> flavor.setDishId(dishDTO.getId()));
            dishFlavorMapper.insert(flavors);
        }
    }

    @Override
    public void stopOrStart(Integer status,Long id) {
        dishMapper.updateStatusById(status, id);
    }

    @Override
    public List<Dish> list(Long categoryId) {
        Dish dish = Dish.builder()
                .categoryId(categoryId)
                .status(StatusConstant.ENABLE)
                .build();

        return dishMapper.list(dish);
    }


    //查询redis中是否存在菜品数据，如果存在直接返回
    //以categoryId进行分类,无需查询数据库
    //不存在，查询数据库，并把查到的数据放到数据库中
    @Override
    public List<DishVO> listWithFlavor(Long categoryId) {
        //构造redis中的key=>dis_categoryId
        String key = CacheConstant.DISH_HEAD + categoryId;

        List<DishVO> list = GsonUtil.fromJsonToList((String) redisTemplate.opsForValue().get(key),DishVO.class);
        log.info("redis菜品数据: {}", list);
        if (list != null) {
            //如果redis中存在菜品数据直接返回
            return list;
        }

        //如果不存在,查询数据库,并放在redis中
        List<DishVO> dishVOList = new ArrayList<>();

        List<Dish> dishFlavors = dishMapper.getDishWithFlavorByCategoryId(categoryId,StatusConstant.ENABLE);
        dishFlavors.forEach(dish -> {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(dish,dishVO);
            dishVO.setFlavors(dish.getFlavorList());
//            log.info("dishVO: {}", dishVO);
            dishVOList.add(dishVO);
        });

        String json = GsonUtil.toJson(dishVOList);
        redisTemplate.opsForValue().set(key,json);

        return dishVOList;
    }

}
